package com.baizhiedu.converter;

import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * ClassName: MyDateConverter
 * Description:
 * Date: 2022/11/21 AM 10:28:02
 * <p>
 * project: spring5
 * package: com.baizhiedu.converter
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
public class MyDateConverter implements Converter<String, Date> {

    private String pattern;

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    /**
     * converter 方法作用：String ---> Date
     * SimpleDateFormat sdf = new SimpleDateFormat();
     * sdf.parse(String) ---> Date
     *
     * @param source 代码配置文件中 日期字符串
     * @return 把转换好的 Date 作为 converter 方法的返回值后，Spring 自动的为 birthday 属性进行注入 (赋值)
     */
    @Override
    public Date convert(String source) {
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern);
            date = sdf.parse(source);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        return date;
    }
}
